package com.taxshare.seller.util;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	/**
	 * pose方式请求
	 * @param url
	 * @return {statusCode : "请求结果状态代码", responseString : "请求结果响应字符串"}
	 */
	public static Map post(String url, Map<String, String> params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost post = postForm(url, params);
//		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//		post.addHeader("Content-Type","text/html;charset=UTF-8");
//		post.setHeader("Content-Type","text/html;charset=UTF-8");
		Map reponseMap = invoke(httpclient, post);		
		httpclient.getConnectionManager().shutdown();
		return reponseMap;
	}
	
	public static Map postJson(String url, String json) throws UnsupportedEncodingException{
		DefaultHttpClient httpclient = new DefaultHttpClient();
		StringEntity s;
		Map reponseMap = null;
		s = new StringEntity(json.toString(),"utf-8");
		s.setContentEncoding("UTF-8");
		s.setContentType("application/json; charset=utf-8");
		HttpPost post = new HttpPost(url);
		reponseMap = invoke(httpclient, post);		
		httpclient.getConnectionManager().shutdown();
		return reponseMap;
	}
	
	
    private static HttpPost postForm(String url, Map<String, String> params){
		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList <NameValuePair>();
		Set<String> keySet = params.keySet();
		for(String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}
		try {			
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return httpost;
	}
    
    
    private static Map invoke(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {
		Map returnMap = new HashMap();
		HttpResponse response = sendRequest(httpclient, httpost);
		String body = paseResponse(response);
		returnMap.put("statusCode", response.getStatusLine().getStatusCode());	// 请求返回结果状态
		returnMap.put("response", body);
		return returnMap;
	}
    
    
    private static HttpResponse sendRequest(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {
		HttpResponse response = null;
		try {
			response = httpclient.execute(httpost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
    
    private static String paseResponse(HttpResponse response) {
		HttpEntity entity = response.getEntity();		
		String charset = EntityUtils.getContentCharSet(entity);
		String body = null;
		try {
			body = EntityUtils.toString(entity,"UTF-8");
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static String sendPost(String url, String param) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder("");
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			// 发送请求参数
			out.write(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			if(out!=null){ try { out.close(); }catch(Exception ex){} }
			if(in!=null){ try { in.close(); }catch(Exception ex){} }
		}
		return result.toString();
	}

}
